<?php
	include "../../config/koneksi.php";
	$ppk = $_POST['ppk'];
	$sukses = 0;
	$gagal = 0;
	echo $_POST['userfile'];
	if ($_FILES[userfile][size] > 0) {

		//get the csv file
		$file = $_FILES[userfile][tmp_name];
		$handle = fopen($file,"r");

		//loop through the csv file and insert into database
		do {
			$no++;
			if($no > 2){
				if ($data[1] != '' && $data[3] != '') {
					$kode = addslashes($data[1]);
					$nama = addslashes($data[2]);
					$harga = addslashes($data[3]);
					$jml = mysql_num_rows(mysql_query("select id_elektromedik from tarif_elektromedik where id_elektromedik = '$kode' and id_ppk = $ppk"));
					if($jml > 0){
						$query = "update tarif_elektromedik set tarif = $harga where id_elektromedik = '$kode' and id_ppk = $ppk";
					}else{
						$query = "insert into tarif_elektromedik (id_ppk,id_elektromedik,tarif) values ($ppk,'$kode',$harga)";
					}
					
					$hasil = mysql_query($query);
					if ($hasil){
						$sukses++;
					}
					else{
						$gagal++;
						$data_gagal[$gagal] = array(
							"id_elektromedik" => "$kode",
							"nama" => "$nama",
							"tarif" => "$harga"
						);
					}
				}else{
					$kosong++;
				}
			}
		} while ($data = fgetcsv($handle,3000,";","'"));
	}
	
	if($gagal > 0){
		$content = "Sukses;$sukses\nGagal;$gagal\n\nNO;KODE;NAMA elektromedik;TARIF\n";
		for($i=1;$i<=$gagal;$i++){
			$content .= "$i;".$data_gagal[$i]['id_elektromedik'].";".$data_gagal[$i]['nama'].";".$data_gagal[$i]['tarif']."\n";
		};

		header("Content-type: text/csv");
		header("Content-Disposition: attachment; filename=Gagal_Import_Elektromedik.csv");
		header("Pragma: no-cache");
		header("Expires: 0");
		echo $content;
	}else{
		echo "<h3>Proses import data selesai.</h3>";
		echo "<p>Jumlah data yang sukses diimport : ".$sukses."<br>";
		echo "Jumlah data yang gagal diimport : ".$gagal."<br>";
		echo "Jumlah data yang memiliki kode atau tarif kosong : ".$kosong."</p>";
	}
?>